package com.ruoyi.web.controller.system;

import java.io.BufferedInputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.doudou.core.container.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.doudou.minio.Minio;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.service.IPvStudentRecordService;
import com.ruoyi.pv.service.IPvUserInfoService;
import com.ruoyi.system.domain.vo.StudentExcelVo;
import com.ruoyi.system.domain.vo.TeacherExcelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 * @author ruoyi
 */
@Api("用户信息")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired private ISysUserService userService;
    @Autowired private ISysRoleService roleService;
    @Autowired private ISysDeptService deptService;
    @Autowired private ISysPostService postService;
    @Autowired private IPvStudentRecordService studentRecordService;
    @Autowired private IPvUserInfoService userInfoService;
    @Autowired private Minio minio;

    /**
     * 获取学生列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list-student")
    @ApiOperation("获取学生列表")
    public TableDataInfo listStudent(SysUser user) {
        startPage();
        user.setDeptId(getDeptId());
        user.setUserType("2");
        List<SysUser> list = userService.getStudentList(user);
        return getDataTable(list);
    }

    /**
     * 获取学生简单列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list-student-simple")
    @ApiOperation("获取学生简单列表")
    public TableDataInfo listStudentSimple() {
        SysUser user = SysUser.builder().deptId(getDeptId()).userType("2").build();
        List<SysUser> list = userService.selectUserListSimple(user);
        return getDataTable(list);
    }

//    /**
//     * 获取当前登录用户的详细信息
//     */
//    @GetMapping("/student")
//    @ApiOperation("获取当前登录用户的详细信息")
//    public AjaxResult getStudent() {
//        return AjaxResult.success(userService.selectUserById(getUserId()));
//    }

    @GetMapping("/student")
    @ApiOperation("获取当前登录用户的详细信息")
    public AjaxResult getStudent() {
        SysUser user = userService.selectUserById(getUserId());
        PvUserInfo userInfo = JSONUtil.parseObj(user.getUserInfo()).toBean(PvUserInfo.class);
        StudentExcelVo build = StudentExcelVo.builder().
                //user
                userId(user.getUserId()).
                avatar(user.getAvatar()).
                nickName(user.getNickName()).
                birthday(user.getBirthday()).
                userName(user.getUserName()).
                email(user.getEmail()).
                identity(user.getIdentity()).
                sex(user.getSex()).
                postsNumber(user.getPostsNumber()).
                //userInfo
                community(userInfo.getCommunity()).
                initialTraining(userInfo.getInitialTraining()).
                practiceRange(userInfo.getPracticeRange()).
                practiceType(userInfo.getPracticeType()).
                posts(userInfo.getPosts()).phonenumber(user.getPhonenumber()).
                postsNumber(user.getPostsNumber()).build();
        return AjaxResult.success(build);
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importTemplate-student")
    public void importTemplateStudent(HttpServletResponse response) {
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);
        util.importTemplateExcel(response, "公卫工作人员数据表模板");
    }

    /**
     * 导入学生
     */
    @Log(title = "用户管理-导入学生", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData-student")
    public AjaxResult importDataStudent(MultipartFile file) throws Exception {
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);
        List<StudentExcelVo> userList = util.importExcel(file.getInputStream());
        if (ObjectUtil.isEmpty(userList)){
            return AjaxResult.error("无法更新空表");
        }
        String craeteUser = getUsername();//获取操作用户的姓名
        Long deptId = getDeptId();//机构
        //今年第一个培训班
        //PvTrainingClass yearFirstClazz = trainingClassService.selectPvTrainingYearFirst(getDeptId());
        SysUser selectUser;
        SysUser user;
        PvUserInfo userInfo;
        StringBuilder successMessage = new StringBuilder();
        StringBuilder failMassage = new StringBuilder();
        int successCount = 0;
        for (StudentExcelVo excelVo : userList){
            if (StrUtil.isBlank(excelVo.getNickName())){
                continue;
            }
//            if (StrUtil.isBlank(excelVo.getUserName())){
//                excelVo.setUserName(excelVo.getPostsNumber());
//            }
            //查询学生是否存在
            try{
                selectUser = userService.selectUserByUserName(excelVo.getUserName());
                user = BeanUtil.copyProperties(excelVo,SysUser.class);
                userInfo = BeanUtil.copyProperties(excelVo,PvUserInfo.class);
                user.setCreateBy(craeteUser);
                if (ObjectUtil.isNotEmpty(selectUser)){//存在，修改用户
                    //填充学生编号
                    user.setUserId(selectUser.getUserId());
                    userInfo.setId(selectUser.getUserId());
                    //修改详细信息
                    userService.updateUser(user);
                    userInfoService.updatePvUserInfo(userInfo);
                    //记录
                    successMessage.append(StudentExcelVo.popUpMassage(
                            "<b>姓名：</b>{}，<b>上岗证：</b>{}",
                            user.getNickName(),
                            user.getPostsNumber()));
                }else{//不存在，新增用户
                    user.setUserType("2");//学生类型
                    user.setDeptId(deptId);//机构
                    user.setPassword("$2a$10$0NZYIllzgtXtxjNpogc4K.h8CT0C1i4vJA1fb/FzjYBODD4gVuchC");//默认密码 【123456】
                    user.setUserInfo(userInfo);//添加学生记录
                    userService.insertUser(user);//添加用户
                    userInfoService.insertPvUserInfo(userInfo);
                    //记录
                    successMessage.append(StudentExcelVo.popUpMassage(
                            "<b>姓名：</b>{}，<b>上岗证：</b>{}",
                            user.getNickName(),
                            excelVo.getPostsNumber()));
                }
                successCount++;
            }catch (Exception e){
                logger.error("",e);
                failMassage.append(StudentExcelVo.popUpMassage(
                        "<b>姓名</b>：{},<b>上岗证：</b>{},<b>失败原因：</b>{}",
                        excelVo.getNickName(),
                        excelVo.getPostsNumber(),
                        e.getMessage()
                ));
            }
        }
        String message = StrUtil.format("数据总量：{}，成功数量：{}",userList.size(),successCount);
        message += successMessage.insert(0,StudentExcelVo.popUpMassage("成功提示："));
        message += failMassage.insert(0,StudentExcelVo.popUpMassage("失败提示："));
        return success(message);
    }

    /**
     * 批量导入学生 社区-姓名.png
     */
    @Log(title = "用户管理-批量导入学生", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData-student-bulk")
    public AjaxResult importDataStudentBulk(MultipartFile file) throws Exception {
        Long deptId = getDeptId();
        List<AjaxResult> zipResult = ListUtil.list(true);
        ZipEntry zipEntry;
        SysUser selectUser;
        ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("GBK"));
        BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String fileName = zipEntry.getName();
            try{
                String fileTrueName = fileName.split("\\.")[0];
                String[] fileTrueNameSplit = fileTrueName.split("-");
                if (fileTrueNameSplit.length != 2){
                    zipResult.add(AjaxResult.success("文件名不符合要求").data(fileName));
                    continue;
                }
                String community = fileTrueNameSplit[0];//社区
                String stuName = fileTrueNameSplit[1];//姓名
                //查询用户
                selectUser = userService.selectUserByNickNameAndPostsNumberAndDeptId(stuName,null,deptId);
                String url = minio.uploadFile(bufferedInputStream, fileName, zipEntry.getSize());
                PvUserInfo userInfo = PvUserInfo.builder().community(community).build();
                if (ObjectUtil.isNotEmpty(selectUser)){//存在，修改用户
                    //填充学生编号
                    selectUser.setAvatar(url);
                    selectUser.setUserInfo(userInfo);
                    //修改详细信息
                    userService.updateUser(selectUser);
                }else{//不存在，新增用户
                    selectUser = new SysUser();
                    selectUser.setUserName(stuName);
                    selectUser.setNickName(stuName);
                    selectUser.setUserType("2");//学生类型
                    selectUser.setDeptId(deptId);//机构
                    selectUser.setPassword("$2a$10$0NZYIllzgtXtxjNpogc4K.h8CT0C1i4vJA1fb/FzjYBODD4gVuchC");//默认密码 【123456】
                    selectUser.setUserInfo(userInfo);
                    userService.insertUser(selectUser);//添加用户
                }
                userInfoService.updatePvUserInfo(userInfo);//修改学生记录
            }catch (Exception e){
                zipResult.add(AjaxResult.success(e.getMessage()).data(fileName));
            }
        }
        zipInputStream.close();
        return AjaxResult.success(zipResult);
    }

    @GetMapping("/start")
    public AjaxResult statr(){
        String name = "E:\\imagess";
        File file = new File(name);

        File[] files = file.listFiles();

        for (File f : files) {
            try{
                String name1 = f.getName();
                String nickName = name1.split("\\.")[0];

                SysUser sysUser = userService.selectUserByNickName(nickName);

                if (ObjectUtil.isNotEmpty(sysUser)){
                    String url = minio.uploadFile(f);
                    userService.updateUser(SysUser.builder().userId(sysUser.getUserId()).avatar(url).build());
                }
            }catch (Exception e){
                logger.error("",e);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 新增学生
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/student")
    public AjaxResult addStudent(@Validated @RequestBody SysUser user) {
        if (StrUtil.isBlank(user.getNickName()) || StrUtil.isBlank(user.getPostsNumber())){
            throw new GlobalException("姓名和上岗证编号不可为空");
        }
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setUserType("2");
        user.setDeptId(getDeptId());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改登录学生信息
     */
    @Log(title = "用户管理-修改学生信息", businessType = BusinessType.UPDATE)
    @PutMapping("/userinfo")
    @ApiOperation("修改登录学生信息")
    public AjaxResult editUserInfo(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
//        if (!userService.checkUserNameUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
//        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
//            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改登录学生信息
     */
    @ApiOperation("修改登录学生信息")
    @Log(title = "修改登录用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/student")
    public AjaxResult editStudent(@RequestBody SysUser excelVo) {
        return editUserInfo(excelVo);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export-student")
    public void exportStudent(HttpServletResponse response, SysUser user) {
        user.setDeptId(getDeptId());
        user.setUserType("2");
        List<SysUser> list = userService.getStudentList(user);
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);
        List<StudentExcelVo> newList = ListUtil.list(true);
        StudentExcelVo vo;
        PvUserInfo userInfo;
        for (SysUser usere : list) {
            userInfo = usere.getUserInfo(PvUserInfo.class);
            vo = StudentExcelVo.builder().
                    community(userInfo.getCommunity()).
                    userName(usere.getUserName()).
//                    reservedOne(Integer.parseInt(userInfo.getReservedOne())).
                    nickName(usere.getNickName()).
                    birthday(usere.getBirthday()).
                    practiceRange(userInfo.getPracticeRange()).
                    practiceType(userInfo.getPracticeType()).
                    posts(userInfo.getPosts()).
                    phonenumber(usere.getPhonenumber()).
                    workUnit(userInfo.getWorkUnit()).
                    docNumber(userInfo.getDocNumber()).build();
            newList.add(vo);
        }
        util.exportExcel(response, newList, "用户数据");
    }


    /**
     * 获取教师列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list-teacher")
    @ApiOperation("获取教师列表")
    public TableDataInfo listTeacher(SysUser user) {
        user.setDeptId(getDeptId());
        user.setUserType("1");
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importTemplate-teacher")
    public void importTemplateTeacher(HttpServletResponse response) {
        ExcelUtil<TeacherExcelVo> util = new ExcelUtil<>(TeacherExcelVo.class);
        util.importTemplateExcel(response, "教师数据表模板");
    }

    @Log(title = "用户管理-导入教师", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData-teacher")
    public AjaxResult importDataTeacher(MultipartFile file) throws Exception {
        ExcelUtil<TeacherExcelVo> util = new ExcelUtil<>(TeacherExcelVo.class);
        List<TeacherExcelVo> userList = util.importExcel(file.getInputStream());
        if (ObjectUtil.isEmpty(userList)){
            return AjaxResult.error("无法更新空表");
        }
        String operName = getUsername();
        Long deptId = getDeptId();
        List<SysUser> sysUsers = BeanUtil.copyToList(userList, SysUser.class);
        for (SysUser student : sysUsers) {
            student.setCreateBy(operName);
            student.setDeptId(deptId);
            userService.insertUser(student);
        }
        return success("上传成功");
    }

    /**
     * 新增教师
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/teacher")
    public AjaxResult addTeacher(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setUserType("1");
        user.setDeptId(getDeptId());
        return toAjax(userService.insertUser(user));
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export-teacher")
    public void exportTeacher(HttpServletResponse response, SysUser user) {
        user.setDeptId(getDeptId());
        user.setUserType("1");
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    //---------------------------------------------------------------
    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理-导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation("根据用户编号获取详细信息")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 获取当前登录人的信息
     */
    @GetMapping("/getInfo2")
    @ApiOperation("根据用户编号获取详细信息")
    public AjaxResult getInfo2() {
        return AjaxResult.success(getLoginUser());
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 真实删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/true/{userIds}")
    public AjaxResult removeTrue(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteTrueUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }
}
